package com.cg.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;

import java.util.Date;
import java.util.Map;

/**
 * JWT工具类
 */
public class JwtUtil {
    
    /**
     * JWT密钥
     */
    private static final String KEY = "DataAnalysisDashboard";
    
    /**
     * Token过期时间：7天
     */
    private static final int END_TIME = 1000 * 60 * 60 * 24 * 7;

    /**
     * 生成Token
     * @param claims 载荷信息
     * @return JWT Token
     */
    public static String genToken(Map<String, Object> claims) {
        return JWT.create()
                .withClaim("claims", claims)
                .withExpiresAt(new Date(System.currentTimeMillis() + END_TIME))
                .sign(Algorithm.HMAC256(KEY));
    }

    /**
     * 解析Token
     * @param token JWT Token
     * @return 载荷信息
     * @throws TokenExpiredException Token过期异常
     */
    public static Map<String, Object> parseToken(String token) {
        return JWT.require(Algorithm.HMAC256(KEY))
                .build()
                .verify(token)
                .getClaim("claims")
                .asMap();
    }
}